package cn.com.zetatech.loader.common.util;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 对与轮询器的消息交互进行加解密
 * @author yyl
 * @since 2023-06-26
 */
public class EncryptUtil {

    private final static String secretKey = "ZetaAYSRMTLoader";

    public static String encrypt(String plainText) {
        try {
            byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
            byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
            for (int i = 0; i < plainBytes.length; i++) {
                plainBytes[i] ^= keyBytes[i % keyBytes.length];
            }
            byte[] encryptedBytes = Base64.getEncoder().encode(plainBytes);
            return new String(encryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }
    }

    public static String decrypt(String encryptedText) {
        try {
            byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
            byte[] encryptedBytes = encryptedText.getBytes(StandardCharsets.UTF_8);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedBytes);
            for (int i = 0; i < decodedBytes.length; i++) {
                decodedBytes[i] ^= keyBytes[i % keyBytes.length];
            }
            return new String(decodedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return null;
        }
    }
}
